package com.mrx.spring.example.security;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.mrx.spring.example.model.po.UserPO;
import com.mrx.spring.example.security.model.XSecurityUser;
import com.mrx.spring.security.model.ApiPermission;
import com.mrx.spring.security.model.SecurityUser;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author Mr.X
 * @since 2023-10-16 16:27
 **/
@Service
public class RedisTokenService {

    private static final Cache<String, SecurityUser> TOKEN_CACHE = Caffeine.newBuilder()
            .expireAfterAccess(Duration.ofMinutes(1))
            .build();

    @NonNull
    public Optional<SecurityUser> loadUserByToken(String token) {
        return Optional.ofNullable(TOKEN_CACHE.getIfPresent(token));
    }

    public String setTokenWithUser(String token, UserPO user) {
        Set<ApiPermission> permissions = user.getPermissions().stream().map(ApiPermission::of).collect(Collectors.toSet());
        TOKEN_CACHE.put(token, XSecurityUser.of(user.getId(), user.getName(), permissions));
        return token;
    }

}
